﻿using System;
using System.Globalization;
using System.Text;
using System.Web;

namespace DotNETStack.Web.Extensions
{
    public static class StringExtensions
    {
        public static String RemoveIllegalCharacters(this String values)
        {
            if (String.IsNullOrEmpty(values))
                return values;

            var sb = new StringBuilder();
            for (int i = 0; i < values.Length; i++)
            {
                if (Char.IsWhiteSpace(values[i]))
                    sb.Append("-");
                if (Char.IsLetterOrDigit(values[i]))
                    sb.Append(values[i]);
            }
            string s = sb.ToString();

            s = RemoveDiacritics(s);
            s = RemoveExtraHyphen(s);

            s = HttpUtility.UrlEncode(s);
            s = s.Replace("%", string.Empty);

            return s;
        }

        public static String RemoveExtraHyphen(this String values)
        {
            if (values.Contains("--"))
            {
                values = values.Replace("--", "-");
                return RemoveExtraHyphen(values);
            }
            return values;
        }

        public static String RemoveDiacritics(this String values)
        {
            string normalized = values.Normalize(NormalizationForm.FormD);
            var sb = new StringBuilder();
            for (int i = 0; i < normalized.Length; i++)
            {
                char c = normalized[i];
                if (CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark)
                    sb.Append(c);
            }
            return sb.ToString();
        }
    }
}